package csu.web.mypetstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import csu.web.mypetstore.mapper.CartMapper;
import csu.web.mypetstore.pojo.DB_Cart;
import csu.web.mypetstore.pojo.Item;
import csu.web.mypetstore.pojo.Product;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.service.ItemService;
import csu.web.mypetstore.service.ProductService;
import csu.web.mypetstore.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, DB_Cart>
    implements CartService{


   @Autowired
   private ItemService itemService;


    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private AccountService accountService;
    @Autowired
    private ProductService productService;
    @Override
    public void insertCart(String workingItemId, String productId, String description, boolean in_stock, Integer quantity, Double listPrice, Double totalCost, String username) {
        int userId=accountService.getUserId(username);
        DB_Cart cart=new DB_Cart();
        cart.setDescription(description);
        cart.setQuanitity(quantity);
        cart.setInStock(in_stock?1:0);
        cart.setItemId(workingItemId);
        cart.setProductId(productId);
        cart.setTotalCost(totalCost);
        cart.setListPrice(listPrice);
        cart.setUserid(userId);
        cartMapper.insert(cart);
    }
    @Override
    public void updateQuantity(Integer quantity, String itemId, String username) {
        double price=itemService.getItemListPrice(itemId);

        double totalCost=price*quantity;


        Wrapper<DB_Cart> wrapper=new UpdateWrapper<DB_Cart>()
                .set("quanitity",quantity)
               .set("total_cost",totalCost)
               .eq("item_id",itemId)
               .eq("userid",accountService.getUserId(username));


        cartMapper.update(wrapper);

    }
    @Override
    public void deleteItem(String itemId, String username) {


           int userId=accountService.getUserId(username);
           Wrapper<DB_Cart> wrapper=new LambdaQueryWrapper<DB_Cart>()
                   .eq(DB_Cart::getItemId,itemId)
                   .eq(DB_Cart::getUserid,userId);

        cartMapper.delete(wrapper);
    }
    @Override
    public void deleteAllItem(String username) {
        int userId=accountService.getUserId(username);
          Wrapper<DB_Cart> wrapper=new QueryWrapper<DB_Cart>()
                  .eq("userid",userId);
          cartMapper.delete(wrapper);
    }
    @Override
    public void decreaseItem(String itemId, int quantity, String userId) {

    }

    @Override
    public double getTotal(Integer userId) {
        List<DB_Cart> cartItems=getCartItems(userId);
        double total=0;
        for(DB_Cart cart:cartItems){
            total+=cart.getTotalCost();
            //System.out.println(total);

        }
        return total;
    }
    public DB_Cart getCartItem(String itemId, int userId) {
        Wrapper<DB_Cart> wrapper=new LambdaQueryWrapper<DB_Cart>()
               .eq(DB_Cart::getItemId,itemId)
               .eq(DB_Cart::getUserid,userId);
        DB_Cart cartItem=cartMapper.selectOne(wrapper);
        return cartItem;
    }

    @Override
    public List<DB_Cart> getCartItems(int userId) {

        Wrapper<DB_Cart> wrapper=new QueryWrapper<DB_Cart>()
               .eq("userid",userId);

        List<DB_Cart> cartItems=cartMapper.selectList(wrapper);
        return cartItems;
    }
    @Override
    public Result getCart(String username) {
        int userId=accountService.getUserId(username);
        List<DB_Cart> cartItems=getCartItems(userId);
        double total=getTotal(userId);
        Map map=new HashMap();
        map.put("cartItems",cartItems);
        map.put("total",total);
        return Result.success(map);
    }
    @Override
    public Result clearCart(String username) {
        int userId=accountService.getUserId(username);
        Wrapper<DB_Cart>wrapper=new LambdaQueryWrapper<DB_Cart>()
                .eq(DB_Cart::getUserid,userId);
        cartMapper.delete(wrapper);
        return Result.success("清空购物车成功");

    }
    @Override
    public Result addToCart(String username, String itemId, int quantity) {
        DB_Cart cartItem=getCartItem(itemId,accountService.getUserId(username));
        Item item=itemService.getItem(itemId);

        if(cartItem==null){
            //如果商品不存在，则向购物车中添加新的一行数据
            Product product=productService.getProduct(item.getProductid());
            DB_Cart cart=new DB_Cart();
            cart.setUserid(accountService.getUserId(username));
            cart.setItemId(itemId);
            cart.setProductId(item.getProductid());
            cart.setListPrice(item.getListprice());
            cart.setTotalCost(itemService.itemPrice(item,quantity));
            cart.setQuanitity(quantity);
            cart.setDescription(product.getDescription());
            cart.setInStock(itemService.isItemInStack(itemId,quantity)?1:0);
            cartMapper.insert(cart);
        }
        else{
            //如果商品存在，则更新购物车中商品的数量和总价

            if(quantity==1)
            {
                DB_Cart cart=getCartItem(itemId,accountService.getUserId(username));
                Wrapper<DB_Cart>wrapper=new UpdateWrapper<DB_Cart>()
                        .set("quanitity",cart.getQuanitity()+1)
                        .set("total_cost",itemService.itemPrice(item,cart.getQuanitity()+1))
                        .eq("item_id",itemId)
                        .eq("userid",accountService.getUserId(username));
                cartMapper.update(wrapper);
            }
            else{
                Wrapper<DB_Cart>wrapper=new UpdateWrapper<DB_Cart>()
                        .set("quanitity",quantity)
                        .set("total_cost",itemService.itemPrice(item,quantity))
                        .eq("item_id",itemId)
                        .eq("userid",accountService.getUserId(username));
                cartMapper.update(wrapper);
            }


        }
        return Result.success("购物车更新成功");
    }
}




